package com.itfetter.search.controller;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itfetter.api.client.ItemClient;
import com.itfetter.api.dto.ItemDTO;
import com.itfetter.common.domain.PageDTO;
import com.itfetter.search.query.ItemPageQuery;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 搜索相关接口
 */
@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
public class SearchController {

    private final ItemClient itemClient;
    private final RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.74.128:9200")));

    /**
     * 搜索商品
     */
    @GetMapping("/list")
    public PageDTO<ItemDTO> search(ItemPageQuery query) throws Exception{
        // 分页查询
        SearchRequest request = new SearchRequest("items");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (!query.getKey().isEmpty()) {
            boolQuery.must(QueryBuilders.matchQuery("name", query.getKey()));
        }
        if (!query.getBrand().isEmpty()) {
            boolQuery.must(QueryBuilders.matchQuery("brand", query.getBrand()));
        }
        if (!query.getCategory().isEmpty()) {
            boolQuery.must(QueryBuilders.matchQuery("category", query.getCategory()));
        }
        if (query.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").lte(query.getMaxPrice()));
        }
        if (query.getMinPrice() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(query.getMinPrice()));
        }
        request.source().query(boolQuery);
//        request.source().size(query.getPageSize());
//        request.source().from((query.getPageNo() - 1) * query.getPageSize());
        if (query.getIsAsc()) {
            request.source().sort(query.getSortBy(), SortOrder.ASC);
        } else {
            request.source().sort(query.getSortBy(), SortOrder.DESC);
        }
        SearchResponse response = null;
        try {
            response = esClient.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SearchHits searchHits = response.getHits();
        List<ItemDTO> list = new ArrayList<>();
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            String doc = hit.getSourceAsString();
            ItemDTO itemDTO = JSONUtil.toBean(doc, ItemDTO.class);
            list.add(itemDTO);
        }
        Page<ItemDTO> page = new Page<>();
        page.setSize(query.getPageSize());
        page.setPages(searchHits.getTotalHits().value);
        PageDTO<ItemDTO> pageDTO = PageDTO.of(page, list);
        esClient.close();
        return pageDTO;
    }


}
